﻿using NxStoreManage;

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace LengthAiCalculate
{
    public partial class EditManufacture : BaseForm
    {
        public Action<bool> DelSuccess;

        public EditManufacture()
        {
            InitializeComponent();
            SetDataGridDefault(dataGridView1, autoGenerateColumns: false, rowHeadersVisible: false);
            SetDataGridDefault(dataGridView2, autoGenerateColumns: false, rowHeadersVisible: false);
        }

        private List<string> s2Select = new List<string>();

        private int dg1SelectRowIndex;

        private void EditManufacture_Load(object sender, EventArgs e)
        {
            List<ListItem> comb3Item = new List<ListItem>();
            comb3Item.Add(new ListItem() { DisplayMember = "大型线", ValueMember = "1" });
            comb3Item.Add(new ListItem() { DisplayMember = "中型线", ValueMember = "2" });
            comb3Item.Add(new ListItem() { DisplayMember = "小型线", ValueMember = "3" });
            BindComboBox(comboBox1, comb3Item);
            comboBox1.SelectedIndex = 0;
            AddCheckBox(dataGridView2, "id", (list) =>
            {
                label7.Text = list.Count.ToString();
            }, out s2Select);
        }

        private void S(string mid)
        {
            dataGridView1.DataSource = nxsqlHelper.GetDataTableFromSql($@"SELECT CONVERT(VARCHAR(10), m.mDatetime, 120) mDatetime,a.planStand,
       m.[zzph],
       m.[rCutGroup],
       m.rLength,
       Sum(cutNum) num,
       m.mid
FROM [PM.AiManufactureResult] m
    INNER JOIN [PM.Ai] a
        ON m.mid = a.mID
WHERE m.mid = '{mid}'
GROUP BY m.rCutGroup,
         m.zzph,
         m.mid,
         a.planSteel,
         a.planSize,
         a.planStand,
         CONVERT(VARCHAR(10), m.mDatetime, 120),
         m.rLength
ORDER BY mDatetime ASC;");
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindComboBox(comboBox2, $@"SELECT DISTINCT a.planID, a.[planName] FROM [PM.Ai] a WHERE a.lineName = '{comboBox1.Text}' AND isEnd = 0 ORDER BY a.planID DESC");
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox2.SelectedValue != null)
            {
                BindComboBox(comboBox3, $@"SELECT a.mID, a.planSize + '(' + a.planSteel + ')' planSize FROM [PM.Ai] a WHERE a.planID = {comboBox2.SelectedValue} ORDER BY a.orderBy ASC;");
            }
        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox3.SelectedValue != null)
            {
                S(comboBox3.SelectedValue.ToString());
            }
        }

        private void dataGridView1_CellClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                dg1SelectRowIndex = e.RowIndex;
                S2(dataGridView1.Rows[e.RowIndex]);
            }
        }

        private void S2(DataGridViewRow row)
        {
            label7.Text = "0";
            if (row != null)
            {
                dataGridView2.DataSource = nxsqlHelper.GetDataTableFromSql($@"SELECT id, mDatetime,resultId,realId,cutNum FROM [PM.AiManufactureResult] WHERE mid = '{row.Cells["mid"].Value}' AND zzph = '{row.Cells["zzph"].Value}' AND rCutGroup = '{row.Cells["rCutGroup"].Value}' AND rLength = {row.Cells["rLength"].Value} AND CONVERT(VARCHAR(10), mDatetime, 120) = '{row.Cells["mDatetime"].Value}'");
            }
            else
            {
                dataGridView2.DataSource = nxsqlHelper.GetDataTableFromSql($@"SELECT id, mDatetime,resultId,realId FROM [PM.AiManufactureResult] WHERE 1=0");
            }
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            dataGridView1.ClearSelection();
            if (dataGridView1.SelectedRows.Count > 0)
            {
                dg1SelectRowIndex = dataGridView1.SelectedRows[0].Index;
                S2(dataGridView1.SelectedRows[0]);
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            Filter();
        }

        private List<string> whereList = new List<string>();

        private void Filter()
        {
            whereList.Clear();
            if (textBox1.Text.Trim() != "")
            {
                whereList.Add($"zzph LIKE '%{textBox1.Text}%'");
            }
            if (textBox2.Text.Trim() != "")
            {
                whereList.Add($"rCutGroup LIKE '%{textBox2.Text}%'");
            }
            dataGridView1.FilterData(string.Join(" AND ", whereList));
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            Filter();
        }

        private void sancToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ShowQuestion("确定删除吗？") == DialogResult.Yes)
            {
                string delId = "";
                string resultId = "";
                string realId = "";
                string num = "0";
                int suc = 0;
                foreach (DataGridViewRow item in dataGridView2.Rows)
                {
                    if (GetCheckValue(item))
                    {
                        num = item.Cells["cutNum"].Value.ToString();
                        if (num.Trim() == "")
                        {
                            num = "1";
                        }
                        delId = item.Cells["id"].Value.ToString();
                        resultId = item.Cells["resultId"].Value.ToString().Trim();
                        realId = item.Cells["realId"].Value.ToString().Trim();
                        if (Up(num, dataGridView1.Rows[dg1SelectRowIndex], resultId, realId, delId)) suc++;
                    }
                }
                if (suc > 0)
                {
                    S(comboBox3.SelectedValue.ToString());
                    Filter();
                    foreach (DataGridViewRow item in dataGridView1.Rows)
                    {
                        if (item.Index == dg1SelectRowIndex)
                        {
                            item.Selected = true;
                            break;
                        }
                        else
                        {
                            item.Selected = false;
                        }
                    }
                    if (dataGridView1.SelectedRows.Count == 0)
                    {
                        if (dataGridView1.Rows.Count > 0)
                        {
                            dataGridView1.Rows[0].Selected = true;
                            dg1SelectRowIndex = 0;
                            S2(dataGridView1.SelectedRows[0]);
                        }
                        else
                        {
                            dg1SelectRowIndex = -1;
                            S2(null);
                        }
                    }
                    else
                    {
                        S2(dataGridView1.SelectedRows[0]);
                        dg1SelectRowIndex = dataGridView1.SelectedRows[0].Index;
                    }
                    DelSuccess?.Invoke(true);
                    ShowMsg("删除成功！");
                }
                else
                {
                    ShowError("删除失败，请重试！");
                }
            }
            else
            {
                ShowError("没有选择要删除的数据！");
            }
        }

        private bool Up(string cutNum, DataGridViewRow row, string resultId, string realId, string delID)
        {
            List<string> upsql = new List<string>();
            string _cutGroup = row.Cells["rCutGroup"].Value.ToString().Trim();
            string _mid = row.Cells["mid"].Value.ToString().Trim();
            string mLength = row.Cells["rLength"].Value.ToString().Trim();
            string[] cutGroup = _cutGroup.Split('=')[1].Split('+');
            upsql.Add("BEGIN TRAN;");
            upsql.Add($"UPDATE [PM.AiSc] SET realNum=realNum-{cutNum} WHERE mID='{_mid}' AND lg={mLength}");
            if (resultId != "")
            {
                upsql.Add($"UPDATE [PM.AiResult] SET num=num+{cutNum} WHERE id={resultId}");
            }
            foreach (var item in cutGroup)
            {
                string[] _temp = item.Split('*');
                string _length = _temp[0];
                string _num = _temp[1] + "*" + cutNum.ToString();
                upsql.Add($"UPDATE [PM.AiJh] SET cutNum=ISNULL(cutNum,0)-{_num} WHERE mId='{_mid}' AND lg={_length}");
            }
            upsql.Add($"DELETE FROM [PM.AiManufactureResult] WHERE id={delID}");
            upsql.Add(@"IF @@ERROR = 0 COMMIT TRAN; ELSE ROLLBACK TRAN;");
            if (realId != "")
            {
                sB_sqlHelper.ExcuteSql($"UPDATE SB_p_CutNumTemp SET num = num - {cutNum} WHERE realID ={realId}");
            }
            return nxsqlHelper.ExcuteSql(upsql) > 0;
        }
    }
}